package demo3;

/**
 * Created with IntelliJ IDEA.
 * Description：
 * User：user
 * DATE:2021-10-29
 * Time:19:32
 */


//数组拷贝有四种方法，但是现在是类无法进行那四种拷贝

class Money implements  Cloneable{
    public double money = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements  Cloneable{
    public int age;
    public Money m = new Money();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person person = (Person) super.clone();
        person.m = (Money) this.m.clone();
        return person;//深克隆，如果还有对象继续克隆
        //return super.clone(); 浅克隆
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}
public class Test {
    public static void main1(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        Person person2 = (Person) person.clone();//受查异常
        person2.age = 199;
        System.out.println(person2);
        System.out.println(person2);
    }
    public static void main(String[] args) throws CloneNotSupportedException {
        //main函数上的引用是在栈上
        Person person = new Person();
        Person person2 = (Person) person.clone();//受查异常
        System.out.println(person.m.money);
        System.out.println(person2.m.money);
        person2.m.money= 198;
        System.out.println(person.m.money);
        System.out.println(person2.m.money);
    }
}
